package com.hanbang.taitaigou.ui.activity.taitaigou;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.model.GetGoodsByID;
import com.hanbang.taitaigou.ui.activity.application.MyApplication;
import com.hanbang.taitaigou.ui.activity.base.BaseActivity;
import com.hanbang.taitaigou.ui.activity.gouwuche.GouWuCheActivity;
import com.hanbang.taitaigou.ui.widget.CircleTextView;
import com.hanbang.taitaigou.ui.widget.NumberSelectView;
import com.hanbang.taitaigou.utils.db.GwcDbUtil;
import com.hanbang.taitaigou.utils.http.BitmapUtil;
import com.hanbang.taitaigou.utils.http.HttpCallBack;
import com.hanbang.taitaigou.utils.http.HttpLocalUtils;
import com.hanbang.taitaigou.utils.http.HttpRequestParams;
import com.hanbang.taitaigou.utils.http.JsonHelper;
import com.hanbang.taitaigou.utils.other.StringUtils;
import com.hanbang.taitaigou.utils.ui.WebViewUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * 商品详情界面
 * Created by fanxin on 2016/3/24.
 */
public class ProductDetailsActivity extends BaseActivity {
    private int id;
    private String title;
    private int shangjiaID;

    private GetGoodsByID getGoodsByID = null;
    //顶部照片
    private LinearLayout ll_photo;
    private ImageView iv_photo;
    //名字
    private TextView tv_name;
    //出售价格
    private TextView tv_money;
    //原价
    private TextView tv_end_money;
    //重量
    private TextView tv_weight;
    //品牌
    private TextView tv_brand;
    // + - 号
    private NumberSelectView numberSelectView;
    //总价
    private TextView tv_total;
    //购物车
    private ImageView iv_gwc;
    //结算
    private Button bt_settlement;
    //网页
    private WebView webView;
    //购物车数量
    private CircleTextView circleTextView;

    //购物车
    private RelativeLayout rl_gwc;
    // + - 号
    private NumberSelectView numberSelectView2;

    private String webHtml = "";

    private int type = -1;


    private RelativeLayout rl_xs;
    private LinearLayout ll_yc;

    public static int shuliang;
    /**
     * 顶部标题
     */
    private TextView top_bar_title;
    private ImageView top_bar_left_iv;
    private RelativeLayout rl_all;
    private TextView top_bar_right_tv;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_details);
        initView();
        setOnClickListener();
        getGoodsByID();
        upDataNumber();
        setAllJiage();

        IntentFilter intentFilter = new IntentFilter(GwcDbUtil.GWC_CHANG_ADD);
        intentFilter.addAction(GwcDbUtil.GWC_CHANG_SUB);
        intentFilter.addAction(GwcDbUtil.GWC_CHANG);
        intentFilter.addAction(GwcDbUtil.GWC_CHANG_CLEAR);
        registerReceiver(broadcastReceiver, intentFilter);

//        WXTextObject wxTextObject = new
    }

    /*
     * 设置点击事件
     */
    private void setOnClickListener() {
        rl_gwc.setOnClickListener(onClickListener);
        top_bar_right_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare();
//                shered(ProductDetailsActivity.this);
            }
        });
    }

    @SuppressWarnings("unused")
    private View.OnClickListener onClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {

                //结算
                case R.id.rl_gwc:
                    Intent intent = new Intent();
                    intent.setClass(ProductDetailsActivity.this, GouWuCheActivity.class);
                    intent.putExtra("order_id", getGoodsByID.getId());
                    intent.putExtra("number", getGoodsByID.getShuliang());
                    startActivityForResult(intent, 999);
                    break;
                default:
                    break;
            }
        }
    };

    /*
     * 初始化view
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void initView() {
        Intent intent = getIntent();
        String sstr = intent.getStringExtra("id");
        type = intent.getIntExtra("type", type);
        id = Integer.valueOf(sstr);
        title = intent.getStringExtra("title");

        rl_gwc = (RelativeLayout) findViewById(R.id.rl_gwc);
        numberSelectView2 = (NumberSelectView) findViewById(R.id.number_select);

        top_bar_title = (TextView) findViewById(R.id.top_bar_title);
        top_bar_left_iv = (ImageView) findViewById(R.id.top_bar_left_iv);
        rl_all = (RelativeLayout) findViewById(R.id.rl_all);
        rl_all.setVisibility(View.VISIBLE);
        top_bar_left_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

//        shangjiaID = Integer.valueOf(intent.getIntExtra("User_id",shangjiaID));

        // 设置顶部的标题
        top_bar_title = (TextView) findViewById(R.id.top_bar_title);
        top_bar_right_tv = (TextView) findViewById(R.id.top_bar_right_tv);
        top_bar_right_tv.setText("分享");


        ll_photo = (LinearLayout) findViewById(R.id.ll_photo);
        iv_photo = (ImageView) findViewById(R.id.iv_photo);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_money = (TextView) findViewById(R.id.tv_money);
        tv_end_money = (TextView) findViewById(R.id.tv_end_money);
        tv_weight = (TextView) findViewById(R.id.tv_weight);
        tv_brand = (TextView) findViewById(R.id.tv_brand);
        numberSelectView = (NumberSelectView) findViewById(R.id.number_select_view);
        tv_total = (TextView) findViewById(R.id.tv_totall);
        iv_gwc = (ImageView) findViewById(R.id.iv_gwc);
        bt_settlement = (Button) findViewById(R.id.bt_settlement);
        circleTextView = (CircleTextView) findViewById(R.id.number);

        webView = (WebView) findViewById(R.id.wv_web);

        rl_xs = (RelativeLayout) findViewById(R.id.rl_xs);
        ll_yc = (LinearLayout) findViewById(R.id.ll_yc);
    }

    //商品数量的回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999 && resultCode == RESULT_OK) {
            getGoodsByID();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }
    //    @Override
//    public void setBackArrows(View back) {
//        super.setBackArrows(back);
//        Intent intent = new Intent();
//        setResult(RESULT_OK, intent);
//    }

    /**
     * 根据商品ID获取商品详情
     */
    private void getGoodsByID() {
        HttpRequestParams httpRequestParams = new HttpRequestParams("GetGoodsByID");
        httpRequestParams.addBodyParameter("id", String.valueOf(id));
//        httpRequestParams.addUserId(userData);
        httpRequestParams.addBodyParameter("User_id", String.valueOf(MyApplication.shangjiaId));
        httpManager.post(httpRequestParams, new HttpCallBack<String>(this, "正在加载...") {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject json = new JSONObject(result);
                    if (json.getInt("status") == 1) {
                        JSONArray resultArray = json.getJSONArray("result");
                        if (resultArray.length() > 0) {
                            getGoodsByID = JsonHelper.parseObject(resultArray.getJSONObject(0), GetGoodsByID.class);
                            if (getGoodsByID != null) {
                                imageManager.bind(iv_photo, HttpLocalUtils.getHttpFileUrl(getGoodsByID.getImg_url()), BitmapUtil.getImageOptionsBuilder().build());
                                tv_name.setText(getGoodsByID.getGname());
                                //零售价
                                tv_money.setText(String.valueOf(getGoodsByID.getSell_price()));
                                //原价
                                tv_end_money.setText("¥" + getGoodsByID.getOriginal_price());
                                getGoodsByID.setShuliang(GwcDbUtil.getGwcIdNumber(id));
                                String ss = getGoodsByID.getContent();
                                WebViewUtils.loadDataWithBaseURL(webView, ss);
                                WebViewUtils.configWebview(webView);

                                numberSelectView.setNumber(getGoodsByID.getShuliang());
                                numberSelectView.setOnItemClickListener(new NumberSelectView.OnItemClickListener() {
                                    @Override
                                    public boolean onAddClick(int num, NumberSelectView view) {
                                        if (GwcDbUtil.addGoodAutoNumber(getGoodsByID.getDbGwcData())) {
                                            getGoodsByID.setShuliang(getGoodsByID.getShuliang() + 1);
                                            String str = sswr(getGoodsByID.getShuliang() * (Double.parseDouble(tv_money.getText().toString())));
//                                            tv_total.setText("总价：" + str);
                                            return true;
                                        }
                                        return false;
                                    }

                                    @Override
                                    public boolean onSubClick(int num, NumberSelectView view) {
                                        if (GwcDbUtil.subGoodAutoNumber(getGoodsByID.getDbGwcData())) {
                                            getGoodsByID.setShuliang(getGoodsByID.getShuliang() - 1);
                                            String str = sswr(getGoodsByID.getShuliang() * (Double.parseDouble(tv_money.getText().toString())));
//                                            tv_total.setText("总价：" + str);
                                            return true;
                                        }
                                        return false;
                                    }
                                });


                                numberSelectView2.setNumber(getGoodsByID.getShuliang());
                                numberSelectView2.setOnItemClickListener(new NumberSelectView.OnItemClickListener() {
                                    @Override
                                    public boolean onAddClick(int num, NumberSelectView view) {
                                        if (GwcDbUtil.addGoodAutoNumber(getGoodsByID.getDbGwcData())) {
                                            getGoodsByID.setShuliang(getGoodsByID.getShuliang() + 1);
                                            String str = sswr(getGoodsByID.getShuliang() * (Double.parseDouble(tv_money.getText().toString())));
//                                            tv_total.setText("总价：" + str);
                                            return true;
                                        }
                                        return false;
                                    }

                                    @Override
                                    public boolean onSubClick(int num, NumberSelectView view) {
                                        if (GwcDbUtil.subGoodAutoNumber(getGoodsByID.getDbGwcData())) {
                                            getGoodsByID.setShuliang(getGoodsByID.getShuliang() - 1);
                                            String str = sswr(getGoodsByID.getShuliang() * (Double.parseDouble(tv_money.getText().toString())));
//                                            tv_total.setText("总价：" + str);
                                            return true;
                                        }
                                        return false;
                                    }
                                });
                                tv_weight.setText("规格：" + (getGoodsByID.getPknum()) + (getGoodsByID.getUnit() == null ? "" : "/" + getGoodsByID.getUnit()));
                                tv_brand.setText("品牌：" + (getGoodsByID.getSubtitle() == null ? "" : getGoodsByID.getSubtitle()));
                            }
                        }
                        rl_xs.setVisibility(View.VISIBLE);
                        ll_yc.setVisibility(View.GONE);
                    } else if (json.getInt("status") == 0) {
                        rl_xs.setVisibility(View.GONE);
                        ll_yc.setVisibility(View.VISIBLE);
                    }
                    if (type == 1) {
                        top_bar_title.setText("商品详情".toString());
                    } else {
                        top_bar_title.setText(title);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * 将double 类型保留小数点两位
     */
    public static String sswr(double f) {
        DecimalFormat df = new java.text.DecimalFormat("#.00");
        return df.format(f);
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.equals(action, GwcDbUtil.GWC_CHANG_ADD)) {
                upDataNumberAdd();
            } else if (TextUtils.equals(action, GwcDbUtil.GWC_CHANG_SUB)) {
                upDataNumberSub();
            } else if (TextUtils.equals(action, GwcDbUtil.GWC_CHANG)) {
                upDataNumber();
            } else if (TextUtils.equals(action, GwcDbUtil.GWC_CHANG_CLEAR)) {
                upDataNumber(0);
            }
        }
    };

    /**
     * 更新购物车的数量   少用
     */
    public void upDataNumber() {
        if (circleTextView != null) {
            upDataNumber(GwcDbUtil.getGwcAllNumber());
            setAllJiage();
        }
    }

    /**
     * 更新购物车的数量
     */
    public void upDataNumber(int number) {
        if (circleTextView != null) {
            circleTextView.setNUmber(number);
            setAllJiage();
        }
    }

    /**
     * 更新购物车的数量 加一
     */
    public void upDataNumberAdd() {
        if (circleTextView != null) {
            circleTextView.setNUmber(circleTextView.getNumber() + 1, true);
            setAllJiage();
        }
    }

    /**
     * 更新购物车的数量 减一
     */
    public void upDataNumberSub() {
        if (circleTextView != null) {
            circleTextView.setNUmber(circleTextView.getNumber() - 1, true);
            setAllJiage();
        }
    }

    /**
     * 设置总价
     */
    private void setAllJiage() {
        tv_total.setText("总价：" + StringUtils.roundDouble(GwcDbUtil.getGwcAlltMoney(GwcDbUtil.SELL_PRICE), 2));
    }


    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
//        oks.disableSSOWhenAuthorize();

//// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
//        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
//        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("太太购未来商圈");
//        oks.setTitle(getString(R.string.app_name));
//        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://taitaigo.cn/");
//        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
//        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        oks.setImagePath("/taitaigou/cache/1462239407385.jpg");//确保SDcard下面存在此张图片
//        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://taitaigo.cn/");
//        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
//        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
//        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://taitaigo.cn/");
//
//
// 启动分享GUI
        oks.show(this);
    }




}
